package com.slkj.util;


import com.slkj.entity.Userinfo;
import com.slkj.mapper.UserMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.aspectj.weaver.ast.Test;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName PmsImage.java
 * @Description TODO
 * @createTime 2020年02月12日 18:48:00
 */
@Component
public class FileManager {


    @Autowired
    UserMapper userMapper;


    private Logger logger = LoggerFactory.getLogger(FileManager.class);

    public com.slkj.entity.File fileupload(MultipartHttpServletRequest multipartHttpServletRequest, String username) throws Exception {
        MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
        if (multipartFile == null) {
            throw new IOException("无文件");
        }
        Userinfo userinfo = userMapper.selectByUsername(username);
        if (userinfo == null) {
            throw new NullPointerException("找不到用户");
        }
        String uploadFileName = multipartFile.getOriginalFilename();
        MultipartFile fileToMultipartFile = multipartFile;
        if (multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".")).equals(".txt")) {
            System.out.println("原始文件名：" + uploadFileName);
            String charset = getCharset(multipartFile.getInputStream());
            File file = fileTurnUTF8(multipartFile.getInputStream(), new File(multipartFile.getOriginalFilename()), charset);
            fileToMultipartFile = fileToMultipartFile(file);
        }


        System.out.println("request.getServletPath()=" + RequestResponseBox.getRequest().getServletPath());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        {
            InputStream fileStream = fileToMultipartFile.getInputStream();
            String uploadPath = RequestResponseBox.getRequest().getSession().getServletContext().getRealPath("/uploadFiles/" + userinfo.getId() + "/" + simpleDateFormat.format(new Date()));
            System.out.println("uploadPath：" + uploadPath);

            File destination = new File(uploadPath, uploadFileName);
            FileUtils.copyInputStreamToFile(fileStream, destination);
            fileStream.close();
        }
        {
            InputStream fileStream = fileToMultipartFile.getInputStream();
            String uploadPath = "src/main/resources/static/uploadFiles/" + userinfo.getId() + "/" + simpleDateFormat.format(new Date());
            System.out.println("uploadPath：" + uploadPath);

            File destination = new File(uploadPath, uploadFileName);
            FileUtils.copyInputStreamToFile(fileStream, destination);
            fileStream.close();
        }


        logger.info("---------------------------->上传文件成功");
        com.slkj.entity.File file = new com.slkj.entity.File();

        String printSize = getPrintSize(multipartFile.getSize());
        file.setInsertTime(new Date());
        file.setFileSize(printSize);
        file.setFileName(multipartFile.getOriginalFilename());
        file.setFileUrl("/uploadFiles/" + userinfo.getId() + "/" + simpleDateFormat.format(new Date()) + "/" + multipartFile.getOriginalFilename());
        return file;
    }


    public ByteArrayInputStream download(String groupName,
                                         String remoteFileName, String specFileName) throws IOException, MyException {
        logger.info("---------------------------->开始下载文件");
        logger.info("---------------------------->参数groupName" + groupName);
        logger.info("---------------------------->参数remoteFileName" + remoteFileName);
        logger.info("---------------------------->参数specFileName" + specFileName);

        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();

        StorageClient storageClient = null;
        try {
            storageClient = GetStorageClient.getStorageClient();
            byte[] fileByte = storageClient.download_file(groupName, remoteFileName);
            ByteArrayInputStream ins = new ByteArrayInputStream(fileByte);
            return ins;
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException("下载文件失败");
        } catch (MyException e) {
            e.printStackTrace();
            throw new MyException("下载文件失败");
        }


    }

    public static String getPrintSize(long size) {
        // 如果字节数少于1024，则直接以B为单位，否则先除于1024，后3位因太少无意义
        double value = (double) size;
        if (value < 1024) {
            return String.valueOf(value) + "B";
        } else {
            value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        }
        // 如果原字节数除于1024之后，少于1024，则可以直接以KB作为单位
        // 因为还没有到达要使用另一个单位的时候
        // 接下去以此类推
        if (value < 1024) {
            return String.valueOf(value) + "KB";
        } else {
            value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
        }
        if (value < 1024) {
            return String.valueOf(value) + "MB";
        } else {
            // 否则如果要以GB为单位的，先除于1024再作同样的处理
            value = new BigDecimal(value / 1024).setScale(2, BigDecimal.ROUND_DOWN).doubleValue();
            return String.valueOf(value) + "GB";
        }
    }

    public static File fileTurnUTF8(InputStream is, File targetFile, String code) throws IOException {
        if (!targetFile.exists()) {
            targetFile.createNewFile();
        }
        BufferedReader br = null;
        BufferedWriter bw = null;
        br = new BufferedReader(new InputStreamReader(is, code));
        bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile), "UTF-8"));
        int i = 0;
        String str = "";
        while ((str = br.readLine()) != null) {
            byte[] bytes = str.getBytes("UTF-8");
            str = new String(bytes, 0, bytes.length);
            bw.write(str + "\r\n");
        }

        br.close();
        bw.close();
        return targetFile;
    }

    public MultipartFile fileToMultipartFile(File file) throws Exception {

        FileInputStream fileInput = new FileInputStream(file);
        MultipartFile toMultipartFile = new MockMultipartFile("file", file.getName(), "text/plain",
                IOUtils.toByteArray(fileInput));
        toMultipartFile.getInputStream();
        return toMultipartFile;

    }

    public static String getCharset(InputStream is) throws IOException {
        BufferedInputStream bin = new BufferedInputStream(is);
        int p = (bin.read() << 8) + bin.read();//读取文件头前16位
        String code = null;
        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16";
                break;
            default:
                code = "GB2312";
        }
        return code;
    }


}
